package com.yeziji.dataCenter.constant;

import cn.hutool.core.io.FileUtil;
import com.yeziji.common.CommonEnum;
import com.yeziji.common.CommonErrorMsg;
import com.yeziji.dataCenter.common.msg.DataCenterErrorMsg;
import com.yeziji.exception.ApiException;
import com.yeziji.utils.expansion.Asserts;
import com.yeziji.utils.expansion.Lists2;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.Set;

/**
 * 数据源模板枚举
 *
 * @author hwy
 * @since 2024/10/26 13:54
 **/
@Slf4j
@Getter
@AllArgsConstructor
public enum DataSourceTemplateEnum implements CommonEnum {
    DRUG_SUPPLY_ERP(0,
            "drug_supply_erp_#{CUSTOM_NAME}",
            "drug_supply_erp_template_base.sql",
            "drug_supply_erp_template",
            Set.of(),
            "药物 erp 服务"),
    ;

    private final int code;
    private final String prefix;
    private final String templateFile;
    private final String templateBase;
    private final Set<String> ignoreTables;
    private final String desc;

    public static DataSourceTemplateEnum getByCode(Integer code) {
        Asserts.notNull(code, CommonErrorMsg.REQUIRED_DATA_IS_NULL);

        return Lists2.filterFirstOpt(DataSourceTemplateEnum.values(), statusEnum -> statusEnum.getCode() == code)
                .orElseThrow(() -> new ApiException(DataCenterErrorMsg.TEMPLATE_NOT_EXISTS));
    }

    /**
     * 获取枚举的模板 sql
     *
     * @return {@link String} sql
     */
    public String getTemplateSql() {
        try {
            byte[] fileData = FileUtil.readBytes("/data-center/sql/" + this.templateFile);
            return new String(fileData);
        } catch (Exception e) {
            log.error("读取本地 sql 失败，开始读取默认 resource sql: {}", e.getMessage());
        }

        // resource path
        ClassPathResource resource = new ClassPathResource("sql/" + this.templateFile);
        try (InputStream inputStream = resource.getInputStream()) {
            byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
            return new String(fileData);
        } catch (IOException e) {
            return "";
        }
    }

    public String getDatabaseName(String name) {
        return this.getPrefix().replace("#{CUSTOM_NAME}", name);
    }
}
